package com.client.controller;

import com.Emplyment.result.Result;
import com.Emplyment.vo.StudyMaterialsVo;
import com.client.service.StudyMaterialsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/study")
@Slf4j
public class StudyMaterialsController {

    @Autowired
    private StudyMaterialsService studyMaterialsService;

    @GetMapping("/materials")
    public Result<List<StudyMaterialsVo>> getStudyMaterials() {
        log.info("获取学习资料");
        List<StudyMaterialsVo> studyMaterials = studyMaterialsService.getStudyMaterials();
        return Result.success(studyMaterials);
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadStudyMaterials(Integer id) throws IOException {
        log.info("下载学习资料");
        StudyMaterialsVo studyMaterials = studyMaterialsService.downloadStudyMaterials(id);
        byte[] file = studyMaterials.getFile();
        // 转换为Resource
        Resource resource = new ByteArrayResource(file);
        String fileName = studyMaterials.getFileName();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);
    }
}
